package com.zhou.controller;

import com.zhou.domain.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/*
			  ________   ___   ___        ___   ________   ___   ___        ___
	 ________|\   __  \_|\  \_|\  \______|\  \_|\   __  \_|\  \_|\  \______|\  \_________
	 \       \ \  \_\ /_\ \  \\ \  \     \ \  \\ \  \_\ /_\ \  \\ \  \     \ \  \        \
	  \       \ \   __  \\ \  \\ \  \     \ \  \\ \   __  \\ \  \\ \  \     \ \  \        \
	   \       \ \  \_\  \\ \  \\ \  \____ \ \  \\ \  \_\  \\ \  \\ \  \____ \ \  \        \
	    \       \ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\        \
	     \       \|_______| \|__| \|_______| \|__| \|_______| \|__| \|_______| \|__|         \
	 	  \___________________________________________________________________________________\

+------------+
|2020/5/5   |
|13:33       |
+------------+
*/
@RestController
@RequestMapping("/consumer")
public class MessageController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;
    @RequestMapping("/findById/{id}")
    public Message findById(@PathVariable("id") String id) {

        //根据名字获取实例
        List<ServiceInstance> instances = discoveryClient.getInstances("eureka-producer");

        if (instances == null && instances.size() == 0) {
            return null;
        }
        //取得实例调用相关方法获取端口、地址
        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        //设置访问路径
        String url = "http://"+host+":"+port+"/msg/findById/"+id;
        return restTemplate.getForObject(url,Message.class);
    }
}
